<template>
    <div class="bg">
        <el-card class="form-card">
            <template #header>
                <div class="card-header">
                    <span>编辑管理员</span>
                </div>
            </template>
            <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username" @change="handleChange" />
                </el-form-item>
                <el-form-item label="姓名" prop="fullname">
                    <el-input v-model="form.fullname" />
                </el-form-item>
                <el-form-item label="角色" prop="role">
                    <el-select v-model="form.role" class="m-2" placeholder="请选择角色">
                        <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="form.sex">
                        <el-radio label="男">男</el-radio>
                        <el-radio label="女">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="手机" prop="tel">
                    <el-input v-model="form.tel" />
                </el-form-item>
                <el-form-item label="邮箱" prop="password">
                    <el-input v-model="form.email" />
                </el-form-item>
                <el-form-item label="头像">
                    <el-upload action="http://localhost:3001/upload/common/" :data="extra" :headers="headers"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                        :on-error="handleUploadError" :show-file-list="false" accept=".jpg,.jpeg,.png"
                        class="avatar-uploader">
                        <img v-if="form.avatar" :src="form.avatar" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button @click="handleSubmit(formRef)" type="primary">保存修改</el-button>
                </el-form-item>
            </el-form>

        </el-card>
    </div>
</template>
<script setup>
import { ref, reactive,watch, watchEffect } from 'vue';
import { useRoute } from 'vue-router';
import { useRouter} from 'vue-router';
import { Plus } from '@element-plus/icons-vue';
// import { ElMessage } from 'element-plus';
import Admin from '@/api/admin';
// import {useRouter} from 'vue-router';
//获取form表单实例化对象
let formRef = ref();
let form = ref({});
//获取当前路径的对象
let route = useRoute();
let router = useRouter();

//加载管理员信息
let loadInfo = async (id) => {
    let { status, msg, data } = await Admin.info({ id });
    if (status) {
        return data;
    }
}
//加载角色列表
let roles = ref([]);
let loadList = async () => {
    let { status, msg, data } = await Admin.role();
    if (status) {
       return data;
    }
};

//保证顺序
// let init = async () => {
//     try {
//         //获取角色列表
//         roles.value = await loadList();
//         //加载管理员信息,还原表单
//         form.value = await loadInfo();
//     } catch (error) {
//         console.log(error);
//     }

// }
// init();



watchEffect(async()=>{
    // console.log(toParams,previewParams);
    try {
        //获取角色列表
        roles.value = await loadList();
        //加载管理员信息,还原表单
        form.value = await loadInfo(route.params.id);
    } catch (error) {
        console.log(error);
    }
});



const imageUrl = ref('');
//提取token
let token = sessionStorage.token;
let headers = { Authorization: `Bearer ${token}` };
//附带参数
let extra = { type: 'avatar' };
const handleAvatarSuccess = ({ status, msg, src }, uploadFile) => {
    //    console.log(response,uploadFile)
    //上传成功
    if (status) {
        //生成图片地址，预览图片
        form.value.avatar = src;
        ElMessage.success(msg);
    } else {
        //上传失败 
        ElMessage.error(msg);
    }
}
const handleUploadError = (error, uploadFile) => {
    console.dir(error)
    let { status, msg } = JSON.parse(error.message);
    ElMessage.error(msg);

};


const beforeAvatarUpload = (rawFile) => {
    //判断图片格式/^image\/[jepg|png|jpg]$/
    let isValid = /^image\/(jpeg|png|jpg)$/.test(rawFile.type);
    if (!isValid) {
        ElMessage.error('头像必须是jpg/png格式!!!')
        return false
    }
    if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2MB!')
        return false
    }
    return true
}
// 表单验证规则
const rules = reactive({
    username: [
        { required: true, message: '请输入账号！', trigger: 'blur' },
        { min: 3, max: 30, message: '账户长度要求3-30个字符之间', trigger: 'blur' },
    ],
    role: [
        { required: true, message: '请选择角色', trigger: 'blur' },
    ],
    fullname: [
        { required: true, message: '请输入姓名！', trigger: 'blur' },
        { min: 2, max: 30, message: '姓名至少2个字符!', trigger: 'blur' },
    ],
    sex: [
        { required: true, message: '请选择性别！', trigger: 'change' },
    ],
    tel: [
        { required: true, message: '请输入手机号码！', trigger: 'blur' },
        { pattern: /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/, message: '手机号码不符合规则！', trigger: 'blur' },
    ],
});
// async function handleChange(){ 
//     let {status,msg,data}= await Admin.check({...form.value})
//     if(status){
//         ElMessage.success(msg)
//     }else{
//         ElMessage.error(msg)
//     }
// }
// let router = uesRouter();
function handleSubmit(formEl) {
    // 校验整个表单
    formEl.validate(async (valid, fields) => {
        if (valid) {
            // 通过校验
            let { status, msg, data } = await Admin.edit({ ...form.value })
            if (status) {

                ElMessage.success(msg)
                router.push('/admin/list');
            } else {

                ElMessage.error(msg)
            }

        }
        else {
            // 校验失败
            console.log('失败字段', fields);
        }
    });
}


</script>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
